package com.gis.service.impl;

import com.gis.dto.MonitorDirectoryDTO;
import com.gis.entity.LayerData;
import com.gis.entity.MonitorDirectory;
import com.gis.mapper.MonitorDirMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
// import com.gis.dto.MonitorDirectory;
import com.gis.service.DirectoryMonitorService;
import com.gis.service.LayerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class DirectoryMonitorServiceImpl extends ServiceImpl<MonitorDirMapper, MonitorDirectory>implements DirectoryMonitorService {

    @Autowired
    private LayerService layerService;
    private final Map<Path, WatchKey> watchKeyMap = new ConcurrentHashMap<>();

    private final Map<Long, MonitorDirectory> directoryMap = new ConcurrentHashMap<>();
    private static final String DATA_FILE_PATH = "monitor_directory_data.ser";
    private WatchService watchService;
    private volatile boolean keepRunning = true;
    private long currentId = 1L;
    public DirectoryMonitorServiceImpl() {
        // 服务初始化时加载历史配置
        super();
    }

    @PostConstruct
    private void init() {
        // 初始化时加载目录配置
        this.startMonitoring();  // 启动监控服务
        loadDirectoryMap();
        log.info("DirectoryMonitorServiceImpl 初始化完成");
    }


    /**
     * 开启watchService服务
     */
    private void startMonitoring() {
        try {
            if (this.watchService == null) {
                this.watchService = FileSystems.getDefault().newWatchService();
                Thread watcherThread = new Thread(this::processEvents);
                watcherThread.setDaemon(true);
                watcherThread.start();
            }
            log.info("watchService已启动，可以添加监控目录");
        } catch (IOException e) {
            throw new RuntimeException("无法创建WatchService", e);
        }
    }
    
    @Override
    public void registerAllDirs(Path start) throws IOException {
        Files.walk(start)
                .filter(Files::isDirectory)
                .forEach(path -> {
                    try {
                        registerDir(path);
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new RuntimeException("无法注册目录: " + path, e);
                    }
                });
    }

    private void registerDir(Path dir) throws IOException {
        WatchKey key = dir.register(
                watchService,
                StandardWatchEventKinds.ENTRY_CREATE
        );
        watchKeyMap.put(dir, key);
    }

    private void processEvents() {
        while (keepRunning) {
            WatchKey key;
            try {
                key = watchService.take();
            } catch (InterruptedException | ClosedWatchServiceException e) {
                break;
            }

            Path dir = null;
            for (Map.Entry<Path, WatchKey> entry : watchKeyMap.entrySet()) {
                if (entry.getValue() == key) {
                    dir = entry.getKey();
                    break;
                }
            }
            if (dir == null) {
                key.reset();
                continue;
            }

            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }

                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path name = ev.context();
                Path child = dir.resolve(name);

                if (kind == StandardWatchEventKinds.ENTRY_CREATE && Files.isRegularFile(child)) {
                    int maxRetries = 4;
                    int delaySeconds = 5;
                    boolean imported = false;

                    for (int attempt = 1; attempt <= maxRetries; attempt++) {
                        try {
                            try (FileInputStream fis = new FileInputStream(child.toFile())) {
                                fis.close();
                            }

                            importSingleFile(child.toFile());
                            imported = true;
                            break;
                        } catch (IOException e) {
                            if (attempt < maxRetries) {
                                try {
                                    Thread.sleep(delaySeconds * 1000L);
                                } catch (InterruptedException ignored) {}
                            }
                        }
                    }

                    if (!imported) {
                        System.err.println("监控导入失败（重试后仍不可访问）： " + child);
                    }
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                watchKeyMap.values().remove(key);
            }
        }
    }


    /**
     * 上传单个文件
     * @param file
     */
    private void importSingleFile(File file) {
        try (FileInputStream fis = new FileInputStream(file)) {
            MultipartFile multipartFile = new MockMultipartFile(
                    file.getName(),
                    file.getName(),
                    "application/octet-stream",
                    fis
            );

            LayerData layerData = layerService.fileNameAnalyse(multipartFile.getOriginalFilename());

            String suffix = getSuffix(file.getName());
            switch (suffix) {
                case "nc":
                case "tiff":
                case "png":
                case "jpg":
                case "jpeg":
                    layerService.uploadFile(layerData, multipartFile);
                    break;
                default:
                    System.out.println("不支持的文件后缀，跳过：" + file.getName());
                    break;
            }
            System.out.println("监控导入成功：" + file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("监控导入失败：" + file.getAbsolutePath());
        }
    }

    /**
     * 获取文件后缀名
     * @param fileName
     * @return
     */
    private String getSuffix(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex == -1 || dotIndex == fileName.length() - 1) {
            return "";
        }
        return fileName.substring(dotIndex + 1).toLowerCase();
    }

    @Override
    @PreDestroy
    public void stopMonitoring() {
        keepRunning = false;
        if (watchService != null) {
            try {
                watchService.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        saveDirectoryMap();
    }


    @Override
    public synchronized MonitorDirectory addMonitorDirectory(MonitorDirectoryDTO monitorDirectoryDTO) {
        // 1.检查path是否存在
        Path monitorPath = Paths.get(monitorDirectoryDTO.getDirName());
        if (!Files.exists(monitorPath) || !Files.isDirectory(monitorPath)) {
            log.error("指定的路径不存在或不是目录：" + monitorPath);
            throw new IllegalArgumentException("指定的路径不存在或不是目录：" + monitorPath);
        }
        // 2.将路径和path保存到数据库中
        MonitorDirectory monitorDirectoryEntity = new MonitorDirectory();
        BeanUtils.copyProperties(monitorDirectoryDTO, monitorDirectoryEntity);
        this.save(monitorDirectoryEntity);

        // 3.开启目录监控
        setActive(monitorDirectoryEntity, keepRunning);

        return monitorDirectoryEntity;
    }

    @Override
    public synchronized boolean removeMonitorDirectory(Long id) {
        MonitorDirectory dir = directoryMap.remove(id);
        if (dir != null) {
            stopMonitoringPath(Paths.get(dir.getDirName()));
            saveDirectoryMap();
            return true;
        }
        return false;
    }

    @Override
    public synchronized boolean updateMonitorDirectory(Long id, String newPath, String newDesc) {
        MonitorDirectory old = directoryMap.get(id);
        if (old == null) return false;
        return true;

        // stopMonitoringPath(old.getDirName());
        // if (startMonitoring(newPath)) {
        //     MonitorDirectory Monitor_t=new MonitorDirectory();
        //     Monitor_t.setId(id);
        //     Monitor_t.setDescription(newDesc);
        //     Monitor_t.setPath(newPath);
        //     directoryMap.put(id, Monitor_t);
        //     saveDirectoryMap();
        //     return true;
        // } else {
        //     startMonitoring(old.getDirName());
        //     directoryMap.put(id, old);
        //     return false;
        // }
    }

    @Override
    public List<MonitorDirectory> listMonitorDirectories() {
        return new ArrayList<>(directoryMap.values());
    }

    private void stopMonitoringPath(Path path) {
        WatchKey key = watchKeyMap.remove(path);
        if (key != null) {
            key.cancel();
        }
    }


    // 保存map到文件
    private void saveDirectoryMap() {
        try (FileOutputStream fos = new FileOutputStream(DATA_FILE_PATH);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(directoryMap);
            System.out.println("监控目录配置已保存至文件：" + DATA_FILE_PATH);
        } catch (Exception e) {
            System.err.println("保存监控配置失败：" + e.getMessage());
        }
    }

    // 从文件加载map
    private void loadDirectoryMap() {
        List<MonitorDirectory> directories = this.list();
        for (MonitorDirectory directory : directories) {
            if (directory.getIsActive()) {
                Path monitorPath = Paths.get(directory.getDirName());
                try {
                    this.registerAllDirs(monitorPath);
                } catch (Exception e) {
                    throw new RuntimeException("加载监控目录失败：" + directory.getDirName(), e);
                }
            }
        }
    }

    public void setActive(MonitorDirectory monitorDirectory, boolean isActive) {
        try {
            Path monitorPath = Paths.get(monitorDirectory.getDirName());
            if(isActive) {
                this.registerAllDirs(monitorPath);  
            } else {
                this.stopMonitoringPath(monitorPath);
            }
            monitorDirectory.setIsActive(isActive);
            this.updateById(monitorDirectory);
        } catch (Exception e) {
            log.error("启动监控目录失败：" + monitorDirectory.getDirName(), e);
            throw new RuntimeException("启动监控目录失败：" + monitorDirectory.getDirName(), e);
        }
    }

    @Override
    public List<File> getFilesByDirId(Long id) {
        List<File> files = new ArrayList<>();
        MonitorDirectory directory = this.getById(id);
        if (directory == null) {
            log.error("未找到ID为 " + id + " 的监控目录");
            throw new IllegalArgumentException("未找到ID为 " + id + " 的监控目录");
        }
        Path dirPath = Paths.get(directory.getDirName());
        if (Files.exists(dirPath) && Files.isDirectory(dirPath)) {
            try {
                Files.walk(dirPath)
                        .filter(Files::isRegularFile)
                        .forEach(path -> files.add(path.toFile()));
            } catch (IOException e) {
                log.error("获取目录文件失败：" + dirPath, e);
            }
        }
        return files;
    }

    @Override
    public HashMap<String, ArrayList<?>> filesUploadHandler(List<File> files){
        HashMap<String, ArrayList<?>> result = new HashMap<>();
        ArrayList<LayerData> successFiles = new ArrayList<>();
        ArrayList<String> failedFiles = new ArrayList<>();
        ArrayList<String> unsupportedFiles = new ArrayList<>();

        // 处理每个文件
        for (File file : files) {
            try {

                FileInputStream fis = new FileInputStream(file);
                MultipartFile multipartFile = new MockMultipartFile(file.getName(), // name
                        file.getName(), // original filename
                        "application/octet-stream", // content type
                        fis // input stream
                );
                LayerData layerData = layerService.fileNameAnalyse(multipartFile.getOriginalFilename());
                switch (file.getName().substring(file.getName().lastIndexOf(".") + 1)
                        .toLowerCase()) {
                    case "nc":
                        layerService.uploadFile(layerData, multipartFile);
                        break;
                    case "tiff":
                        layerService.uploadFile(layerData, multipartFile);
                        break;
                    case "png":
                        layerService.uploadFile(layerData, multipartFile);
                        break;
                    case "jpg":
                        layerService.uploadFile(layerData, multipartFile);
                        break;
                    case "jpeg":
                        layerService.uploadFile(layerData, multipartFile);
                        break;
                    default:
                        unsupportedFiles.add(file.getName());
                        break;
                }
                successFiles.add(layerData);

                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
                failedFiles.add(file.getName());
                continue;
            }
            // 如果是NetCDF文件
        }
        result.put("successFiles", successFiles);
        result.put("failedFiles", failedFiles);
        result.put("unsupportedFiles", unsupportedFiles);
        return result;
    }
}

